package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.CreateNotification;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

public class CreateStory extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/** * @see HttpServlet#HttpServlet() */
	public CreateStory() {
		super(); // TODO Auto-generated constructor stub
	}
	
	/**
	 * Creates a story fragment. This operation can only be performed by a registered user. The created story fragment can
	 * be linked to a fragment in an already existing story or it can create a new story. Based on the choice of the owner
	 * of the story, this fragment can be linked story fragments by all other users in the system (public) or a group of users
	 * (private). If the fragment is successfully created, followers of the owner of this fragment are notified. If the fragment
	 * is linked to a fragment in already existing story, then the owner of each fragment which is a part of the story is sent a
	 * notification.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		String f_linkingOption = request.getParameter("linking_option");
		String f_allowedList = "public";
		// If the user selects private linking then get the list of the users who are allowed to link to this fragment.
		if (f_linkingOption.equals("private")) {
			f_allowedList = request.getParameter("allowed_list");
		}

		// Replace non-English characters with English characters 
		String f_title = Utilities.convertToEnglish(request.getParameter("title"));
		String f_body = Utilities.convertToEnglish(request.getParameter("body"));
		String f_locationDescription = Utilities.convertToEnglish(request.getParameter("location"));
		String f_coordinates = request.getParameter("coordinates");
		double f_locationX = Double.parseDouble(f_coordinates.split(",")[0]);
		double f_locationY = Double.parseDouble(f_coordinates.split(",")[1]);
		// If the user uploads a picture for this fragment, store the link of it. Imgur API is used here.
		String f_media = request.getParameter("media_link");
		int f_totalRating = 0;
		int f_ratingCount = 0;
		PreparedStatement stmt = null;
		String sqlStatement = null;
		ResultSet rs = null;
		int newStoryID = -1;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				CreateNotification newNotification = new CreateNotification();
				String username;
				if (f_requestType.equals("Web")) {
					username = (String) request.getSession().getAttribute("username");
					// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
					if (username == null) {
						response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
						return;
					}
				} else {
					username = request.getParameter("username");
				}
				int f_owner = Utilities.getUserId(conn, username);
				java.util.Date today = new java.util.Date();
				Timestamp f_timeStamp = new Timestamp(today.getTime());
				sqlStatement = "INSERT INTO "
						+ TableNames.STORIES_TABLE
						+ "(s_id,date,title,location,owner,parent,x_coord,y_coord,body,media,totalRating,ratingCount,allowedList) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
				stmt = conn.prepareStatement(sqlStatement,
						Statement.RETURN_GENERATED_KEYS);

				stmt.setNull(1, Types.INTEGER);
				stmt.setTimestamp(2, f_timeStamp);
				stmt.setString(3, f_title);
				stmt.setString(4, f_locationDescription);
				stmt.setInt(5, f_owner);

				// If this fragment is linked to another story fragment, get the ID of the story fragment that it is linked to.
				String parent_id = request.getParameter("parent_id");
				if (parent_id != null) {
					int f_parent = Integer.parseInt(parent_id);
					stmt.setInt(6, f_parent);
				} else {
					stmt.setNull(6, Types.INTEGER);
				}

				stmt.setDouble(7, f_locationX);
				stmt.setDouble(8, f_locationY);
				stmt.setString(9, f_body);
				stmt.setString(10, f_media);
				stmt.setInt(11, f_totalRating);
				stmt.setInt(12, f_ratingCount);
				stmt.setString(13, f_allowedList);

				/*
				 * If databaseResponse is "1", then entry insertion is SUCCESS
				 * If databaseResponse is "0", then entry insertion is FAILED
				 * 
				 * SUCCESS -> Return TRUE as JSON Object FAIL -> Return FALSE as
				 * JSON Object
				 */
				int databaseResponse = stmt.executeUpdate();
				rs = stmt.getGeneratedKeys();
				// Upon successful creation of the fragment, get the ID of it
				if (rs.next()) {
					newStoryID = rs.getInt(1);
				}
				request.setCharacterEncoding("utf8");
				response.setContentType("application/json");
				boolean successStatus = false; // as default
				if (databaseResponse == 1) {
					// If creation is successful, then insert the tags associated with this fragment to the Tag table
					int tagDatabaseResponse = 0;
					String tags = Utilities.convertToEnglish(request.getParameter("tags"));
					String[] tagArray = tags.split(",");
					int f_tagCount = tagArray.length;
					stmt = conn.prepareStatement("INSERT INTO "
							+ TableNames.TAGS_TABLE + "(s_id,tag) VALUES(?,?)");
					stmt.setInt(1, newStoryID);
					for (int idx = 0; idx < f_tagCount; idx++) {
						String tag = tagArray[idx];
						stmt.setString(2, tag);
						tagDatabaseResponse = stmt.executeUpdate();
					}
					if (tagDatabaseResponse == 1) {
						/*
						 * If both operations are executed correctly, then create notifications for the relevant users.
						 * Please refer to CreateNotification.java in utils package to get a more detailed description
						 * of the notification system. 
						 */
						newNotification.createFollowerContentNotification(f_owner, newStoryID);
						if (parent_id != null) {
							newNotification.createLinkedStoryNotification(f_owner, newStoryID);
						}
						successStatus = true;
					} else {
						successStatus = false;
					}
				} else if (databaseResponse == 0) {
					successStatus = false;
				} else {
					// TODO must be handled !!
				}
				
				/*
				 * Based on the source of the request (Web or Android client) different responses are created.
				 * Android clients are returned a JSONObject while Web clients are returned a HTTPServletResponse
				 * object.
				 */
				if (f_requestType.equals("Android")) {
					JSONObject successStatusJsonObject = new JSONObject();
					try {
						successStatusJsonObject.put("success", successStatus);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(successStatusJsonObject.toString());
				} else if (f_requestType.equals("Web")) {
					// Redirect to main page after operation is completed.
					request.setAttribute("createStorySuccess", successStatus);
					request.getRequestDispatcher("MainPage").forward(request,
							response);
				} else {
					// TODO handle?
				}

			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 * response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		// TODO Auto-generated method
		processRequest(request, response);
	}

	/**
	 * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 * response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		// TODO Auto-generated method
		processRequest(request, response);
	}

}
